<?php
/**
 * Created by PhpStorm.
 * User: another
 * Date: 2019-04-25
 * Time: 10:33
 */
namespace App\Models;

use App\Http\Controllers\Api\DragonController;
use App\Http\Controllers\Api\NoteCodeController;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Zizaco\Entrust\Traits\EntrustUserTrait;

class Member extends Authenticatable implements JWTSubject
{
    use Notifiable;
    use EntrustUserTrait;

    /**
     * 与模型关联的数据表
     *
     * @var string
     */
    protected $table = 'member';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'mobile', 'password','description','openid','nickname','avatar','user_id','openid','nickname','avatar'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    // Rest omitted for brevity

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    /**
     * @param $where
     * @param $key
     * @return mixed
     */
    public function getMember($where,$key)
    {
        return $this->where($where)->first($key);
    }

    /**
     * @param $where
     * @param $data
     * @return mixed
     */
    public function updMember($where,$data)
    {
        return $this->where($where)->update($data);
    }

    public function getMemberList($where)
    {
        return $this
            ->when(!empty($where['nickname']),function ($query) use ($where){
                $query->where('nickname','like','%'.$where['nickname'].'%');
            })
            ->when(!empty($where['mobile']),function ($query) use ($where){
                $query->where('mobile',$where['mobile']);
            })
            //开始时间
            ->when(!empty($where['onset_time']),function ($query) use ($where){
                $query->where('created_at','>',$where['onset_time']);
            })

            //结束时间
            ->when(!empty($where['over_time']),function ($query) use ($where){
                $query->where('created_at','<',$where['over_time']);
            })
            ->orderBy('id','desc')
            ->select([
                'id',
                'nickname',
                'name',
                'mobile',
                'is_check',
                'created_at',
            ])
            ->paginate($where['page_size']);
    }
    /**
     * 龙卡用户列表
     * @param $where
     * @return mixed
     */
    public function getMemberListDragon($where)
    {
        $members = $this
            ->join('member_basic', 'member.id', '=', 'member_basic.uid')
            ->join('member_enterprise', 'member.id', '=', 'member_enterprise.uid')
            ->join('member_dragon', 'member.id', '=', 'member_dragon.uid')

            ->where('member.is_check','!=','0')
            //判断是否生成龙卡
            ->when($where['is_mark'] > 0,function ($query) use ($where){
                if(in_array($where['is_mark'],['1','2','3'])){
                    $query->where('member_dragon.status',$where['is_mark']);
                }elseif ($where['is_mark'] == 4){
                    $query->where('member_dragon.is_check',1);
                }
            })

            //是否审核
            ->when(!empty($where['is_check']),function ($query) use ($where){
                if($where['is_check'] != 10){
                    $query->where('member.is_check',$where['is_check']);
                }
            })

            //用户姓名
            ->when(!empty($where['name']),function ($query) use ($where){
                $query->where('member_basic.name','like','%'.$where['name'].'%');
            })

            //用户电话
            ->when(!empty($where['mobile']),function ($query) use ($where){
                $query->where('member_basic.mobile','like','%'.$where['mobile'].'%');
            })

            ->when(!empty($where['card_num']),function ($query) use ($where){
                $query->where('member_dragon.card_num',$where['card_num']);
            })

            //开始时间
            ->when(!empty($where['onset_time']),function ($query) use ($where){
                $onset_time = strtotime($where['onset_time']);
                if(in_array($where['is_check'],['10','2'])){
                    $query->where('member_basic.addtime','>',$onset_time);
                }else{
                    if($where['is_mark'] == 4){
                        $query->where('member_dragon.over_time','>',$onset_time);
                    }else{
                        $query->where('member_dragon.updtime','>',$onset_time);
                    }
                }
            })

            //结束时间
            ->when(!empty($where['over_time']),function ($query) use ($where){
                $over_time = strtotime($where['over_time']);
                if(in_array($where['is_check'],['10','2'])){
                    $query->where('member_basic.addtime','<',$over_time);
                }else{
                    if($where['is_mark'] == 4){
                        $query->where('member_dragon.over_time','<',$over_time);
                    }else{
                        $query->where('member_dragon.updtime','<',$over_time);
                    }
                }
            })
            ->orderBy('member_basic.addtime','desc')
            ->select([
                'member.id as uid',
                'member.user_id',
                'member.is_check',
                'member_basic.name',
                'member_basic.mobile',
                'member_basic.identity_num',
                'member_basic.talents_type',
                'member_enterprise.enterprise_name',
                'member_basic.addtime',
                'member_basic.updtime',
                'member_dragon.card_num',
                'member_dragon.first_trial_user',
                'member_dragon.first_remark',
                'member_dragon.first_trial_time',
                'member_dragon.second_trial_user',
                'member_dragon.second_remark',
                'member_dragon.second_trial_time',
                'member_dragon.over_time',
                'member_dragon.hairpin_time',
                'member_dragon.status',
                'member_dragon.is_freeze',
            ])
            ->paginate($where['page_size']);

        $dragon = new DragonController();
        $basice = $dragon->basiceType();

        foreach ($members as $key=>$value){
            $members[$key]->talents_type = $basice['talents_type'][$value->talents_type];
            if(in_array($where['is_check'],['10','2'])){
                $members[$key]->time = date('Y-m-d H:i:s',$value->addtime);
                if($value->second_trial_user > 0){
                    $members[$key]->trial_use = $this->getAdminName($value->second_trial_user);
                    $members[$key]->remark = $value->second_remark;
                    $members[$key]->trial_time = date('Y-m-d H:i:s',$value->second_trial_time);
                }elseif ($value->first_trial_user > 0){
                    $members[$key]->trial_use = $this->getAdminName($value->first_trial_user);
                    $members[$key]->remark = $value->first_remark;
                    $members[$key]->trial_time = date('Y-m-d H:i:s',$value->first_trial_time);
                }else{
                    $members[$key]->trial_use = '';
                    $members[$key]->remark = '';
                    $members[$key]->trial_time = '';
                }
            }else{
                $members[$key]->time = date('Y-m-d H:i:s',$value->addtime);
                if($value->second_trial_user == 0){
                    $members[$key]->trial_use = $this->getAdminName($value->first_trial_user);
                    $members[$key]->remark = $value->first_remark;
                    $members[$key]->trial_time = date('Y-m-d H:i:s',$value->first_trial_time);
                }else{
                    $members[$key]->trial_use = $this->getAdminName($value->second_trial_user);
                    $members[$key]->remark = $value->second_remark;
                    $members[$key]->trial_time = date('Y-m-d H:i:s',$value->second_trial_time);
                }
            }

            if(empty($value->over_time)){
                $members[$key]->over_time = '';
            }else{
                $members[$key]->over_time = date('Y-m-d',$value->over_time);
            }

            if(empty($value->hairpin_time)){
                $members[$key]->hairpin_time = '';
            }else{
                $members[$key]->hairpin_time = date('Y-m-d H:i:s',$value->hairpin_time);
            }

            unset($value['addtime']);
            unset($value['updtime']);
            unset($value['first_trial_user']);
            unset($value['first_remark']);
            unset($value['first_trial_time']);
            unset($value['second_trial_user']);
            unset($value['second_remark']);
            unset($value['second_trial_time']);
        }

        return $members;
    }

    /**
     * 获取后台用户数据
     * @param $id
     * @return mixed
     */
    public function getAdminName($id)
    {
        $adminModel = new Admin();
        $admin = $adminModel->where('id',$id)->first(['name']);
        if(empty($admin))
            return '';
        return $admin->name;
    }

    /**
     * 获取用户数据
     * @param $uid
     * @return mixed
     */
    public function getMemberDragon($uid)
    {
        $memberBasicModel = new MemberBasic();
        $basic = $memberBasicModel->getBasic(['uid'=>$uid]);

        $qiyeModel = new MemberEnterprise();
        $qiye = $qiyeModel->getEnterprise(['uid'=>$uid]);

        $memberInfoModel = new MemberBasicInfo();
        $memberInfo = $memberInfoModel->getBasicInfo(['uid'=>$uid]);


        $data['name'] = $basic->name;
        $data['identity_num'] = $basic->identity_num;
        if($basic->sex == 1){
            $data['sex'] = '男';
        }else{
            $data['sex'] = '女';
        }
        $data['identity_num'] = $basic->identity_num;
        $data['enterprise_name'] = $qiye->enterprise_name;
        $data['jz_address'] = $basic->jz_address;
        $data['avatar'] = $memberInfo->avatar;
        return $data;
    }

    public function addMember($data)
    {
        $bool = $this->create($data);
        return $bool?['code'=>'1','message'=>'授权成功']:['code'=>'0','message'=>'授权失败'];
    }


    public function getDetails($uid)
    {
        $enterpriseModel = new MemberEnterprise();
        $qiye = $enterpriseModel->getEnterprise(['uid'=>$uid])->toArray();

        $baseModel = new MemberBasic();
        $ziliao = $baseModel->getBasic(['uid'=>$uid])->toArray();

        $xqModel = new MemberBasicInfo();
        $xaingqing = $xqModel->getBasicInfo(['uid'=>$uid])->toArray();
        $xaingqing['come_district_time'] = date('Y-m-d',$xaingqing['come_district_time']);
        if(empty($xaingqing['service_project'])){
            $xaingqing['service_project'] = [];
        }else{
            $xaingqing['service_project']= explode(',',$xaingqing['service_project']);
        }

        $data = array_merge($qiye,$ziliao,$xaingqing);
        unset($data['addtime']);
        unset($data['updtime']);
        return $data;
    }

    public function updMobile($data)
    {
        if(empty($data['mobile'])){
            return ['code'=>'0','message'=>'手机号不能为空'];
        }

        if(empty($data['code'])){
            return ['code'=>'0','message'=>'验证码不能为空'];
        }


        $code = new NoteCodeController();
        $code_bool = $code->verifyCode($data);
        if($code_bool['code'] == 0){
            return $code_bool;
        }
        $temp['mobile'] = $data['mobile'];
        DB::beginTransaction();
        try{
            $baseModel = new MemberBasic();
            $this->updMember(['id'=>$data['user']['uid']],$temp);
            $baseModel->updBasic($data['user']['uid'],$temp);
            DB::commit();
            return ['code'=>'1','message'=>'修改成功'];
        }catch (\Exception $e){
            DB::rollBack();
            return ['code'=>'0','message'=>'修改失败'];
        }
    }
}
